package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.LogRecord;

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // 用于检查路径是否匹配的工具，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求的uri
        String requestURI = request.getRequestURI();

        // 定义不需要处理的请求路径
        String[] uris= new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        log.info("拦截到路径：{}", requestURI);

        // 若uri在uris中，表示不需要处理，可以直接放行
        boolean ok = check(uris, requestURI);
        if(ok) {
            filterChain.doFilter(request, response);
            return;
        }

        // 1、若需要处理，需要拿到用户的session
        Long empId = (Long)request.getSession().getAttribute("emp");
        if(empId != null) {

            // 使用先线程存放登录用户的id值
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }

        // 2、移动端用户登录判断
        Long userId = (Long)request.getSession().getAttribute("user");
        if(userId != null) {

            // 使用先线程存放登录用户的id值
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");

        // 若session为空，根据前端的代码，需要返回一个错误消息。
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    public boolean check(String[] uris, String uri) {
        for(String s : uris) {
            boolean match = PATH_MATCHER.match(s, uri);
            if(match) {
                return true;
            }
        }
        return false;
    }
}
